<template>
    <div>
      <div class="shopcart">
        <div class="content" @click="toggleList">
          <div class="content-left">
              <div class="logo-wrapper">
                  <div class="logo" :class="{'highlight':totalCount>0}">
                      <i class="icon-shopping_cart" :class="{'highlight':totalCount>0}"></i>
                  </div>
                  <!-- totalCount>0 时才会显示出这个层 -->
                  <div class="num" v-show="totalCount>0">{{totalCount}}</div>
              </div>
              <div class="price" :class="{'highlight':totalPrice>0}">￥{{totalPrice}}</div>
              <div class="desc">另需配送费￥{{deliveryPrice}}元</div>
              <!-- <div class="desc">{{listShow}}</div> -->
          </div>
          <div class="content-right" @click.stop="pay">
            <div class="pay" :class="payClass">
              {{payDesc}}
            </div>
          </div>
        </div>
        <div class="ball-container">
          <div>
            <transition name="drop"
            @before-enter="beforeEnter"
            @enter="enter"
            @after-enter="afterEnter">
              <div class="ball" v-for="ball in balls" v-show="ball.show" :key="ball">
                <div class="inner inner-hook"></div>
              </div>
            </transition>
          </div>
        </div>
        <transition name="fold">
          <div class="shopcart-list" v-show="listShow">
            <div class="list-header">
              <h1 class="title">购物车</h1>
              <span class="empty" @click="empty">清空</span>
            </div>
            <div class="list-content" ref="listContent">
              <ul>
                <li class="food" v-for="food in selectFoods" :key="food">
                  <span class="name">{{food.name}}</span>
                  <div class="price">
                    <span>￥{{food.price*food.count}}</span>
                  </div>
                  <div class="cartcontrol-wrapper">
                    <cartcontrol @getAddButtonElements="takeAddButtonElements" :food="food"></cartcontrol>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </transition>
      </div>
      <transition name="mask">
        <div class="list-mask" v-show="listShow" @click="hideListAndMask"></div>
      </transition>
    </div>
</template>

<script>
import cartcontrol from '../cartcontrol/cartcontrol.vue';
import BScroll from 'better-scroll';

export default {
  data() {
    return {
      balls: [ // 用来维护每个小球的状态，刚开始小球是默认隐藏的
        {
          show: false
        },
        {
          show: false
        },
        {
          show: false
        },
        {
          show: false
        },
        {
          show: false
        },
        {
          show: false
        },
        {
          show: false
        },
        {
          show: false
        }
      ],
      dropBalls: [], // 已经下落的小球
      fold: true // 默认列表折叠
    };
  },
  components: {
    cartcontrol: cartcontrol
  },
  created() {
    this.$nextTick(() => {
      this._initScroll();
    });
  },
  methods: {
    takeAddButtonElements(element) {
        this.drop(element);
    },
    setFoldValueToTrue() {
      this.fold = true;
    },
    pay() {
      if (this.totalPrice < this.minPrice) {
        return;
      };
      window.alert('请支付：￥' + this.totalPrice);
    },
    hideListAndMask() {
      this.fold = true;
    },
    _initScroll() {
      this.scroll = new BScroll(this.$refs.listContent, {
      click: true
      });
    },
    empty() {
      this.selectFoods.forEach((food) => { // 循环购物车中的food，将其count属性值置为0
        food.count = 0;
      });
      // this.totalCount = 0; // 注意：千万不要使用这种方法置0，因为这个方法只是将data中的这个totalCount变量置为0，而没有将商品的food.count属性置为0。
      // this.fold = true; // 清空列表时要关闭购物车
    },
    toggleList() {
      if (this.totalCount <= 0) {
        this.fold = true;
        console.log('现在totalCount<=0，所以我被触发了');
        // return;
      } else {
        this.fold = !this.fold;
        console.log('我是toggleList中的' + this.fold);
      }
    },
    drop(element) {
      // console.log(element);
      for (let i = 0; i < this.balls.length; i++) {
        let ball = this.balls[i];
        if (!ball.show) {
          ball.show = true; // 关键的一句话，能触发动画
          ball.el = element; // 用一个el属性去保留这个element
          this.dropBalls.push(ball);
          console.log('i am changed');
          return;
        }
      }
    },
    beforeEnter(el) {
      console.log(el);
      let count = this.balls.length;
      console.log(count);
      while (count--) {
        let ball = this.balls[count];
        if (ball.show) {
          let rect = ball.el.getBoundingClientRect();
          console.log(rect);
          let x = rect.left - 32;
          let y = -(window.innerHeight - rect.top - 75);
          el.style.display = '';
          el.style.webkitTransform = `translate3d(0,${y}px,0)`;
          el.style.transform = `translate3d(0,${y}px,0)`;
          let inner = el.getElementsByClassName('inner-hook')[0];
          inner.style.webkitTransform = `translate3d(${x}px,0,0)`;
          inner.style.transform = `translate3d(${x}px,0,0)`;
          inner.style.backgroundColor = '#389fdb';
        }
      }
    },
    enter(el, done) {
      /* eslint-disable no-unused-vars */
      let rf = el.offsetHeight; // 加了上面的注释，这个rf变量即使没有被引用也不会报错
      // 体验优化，异步执行下落动画
      this.$nextTick(() => {
        console.log('haha1');
        el.style.webkitTransform = 'translate3d(0, 0, 0)';
        el.style.transform = 'translate3d(0, 0, 0)';
        let inner = el.getElementsByClassName('inner-hook')[0];
        console.log(inner);
        inner.style.webkitTransform = 'translate3d(0, 0, 0)';
        inner.style.transform = 'translate3d(0, 0, 0)';
        inner.style.backgroundColor = 'red';
        el.addEventListener('transitionend', done);
        // done();
      });
    },
    afterEnter(el) {
      let ball = this.dropBalls.shift();
      if (ball) {
        ball.show = false;
        el.style.display = 'none';
        console.log('haha2');
      }
    }
  },
  // props: ['deliveryPrice', 'minPrice', 'selectFoods'],
  props: {
    deliveryPrice: {
      type: Number,
      default: 0
    },
    minPrice: {
      type: Number,
      default: 0
    },
    selectFoods: {
      type: Array,
      default() {
        return [
          // {
          //   price: 18,
          //   count: 2
          // }
        ];
      }
    }
  },
  computed: {
    totalPrice() {
      let total = 0;
      this.selectFoods.forEach((food) => {
        total += food.price * food.count;
      });
      return total;
    },
    totalCount() {
      let count = 0;
      this.selectFoods.forEach((food) => {
        count += food.count;
      });
      return count;
    },
    payDesc() {
      if (this.totalPrice === 0) {
        return `￥${this.minPrice}元起送`; // 有变量时可以用反引号 `` 来写要返回在字符串等
      } else if (this.totalPrice < this.minPrice) {
        let diff = this.minPrice - this.totalPrice;
        return `还差￥${diff}元起送`;
      } else {
        return '去结算'; // 没有变量时就用普通的单引号来返回信息
      }
    },
    payClass() {
      if (this.totalPrice < this.minPrice) {
        return 'not-enough';
      } else {
        return 'enough';
      }
    },
    listShow: {
      get() { // 使用get、set才能在计算属性里面更改值，get用来获取值
        console.log('我是listShow的get中的触发！' + !this.fold);
        if (this.totalCount === 0) {
        //   console.log('totalCount值为：' + this.totalCount);
          // this.empty();
        //   console.log('this.fold值：' + this.fold + '，返回的是!this.fold:' + !this.fold);
          if (this.fold === false) { // 这种情况是列表已经打开时，我们通过减号按钮将商品数量值为0，而这时的this.fold是为false的（因为此时listShow为true，所以this.fold肯定是为false）
            this.setFoldValueToTrue(); // 我们通过这个函数再将this.fold值设置为true
            // console.log('设置后的this.fold值为' + this.fold);
          }
          return !this.fold; // 返回false，关闭商品列表
        }
        // console.log('现在totalCount值为：' + this.totalCount + '，应该返回!this.fold值为：' + !this.fold);
        return !this.fold; // !this.fold是读取fold的值，并取反，而不是改变fold的值，通过点击取来toggle fold值，并返回
      }
        /**
         * 以下添加滚动函数的时机好像有点不对，我们应该在methods中去定义一个初始化滚动列表的事件，然后在created中去调用它
        */
        // if (show) {
        //   this.$nextTick(() => {
        //     if (!this.scroll) {
        //       this.scroll = new BScroll(this.$refs.listContent, {
        //       click: true
        //       });
        //     } else {
        //       this.scroll.refresh();
        //     }
        //   });
        // }
        // return show;
    }
  }
};
</script>

<style lang="stylus">
@import '../../common/stylus/mixin.styl';

  .shopcart
    position fixed
    left 0
    bottom 0
    z-index 50
    width 100%
    height 48px
    .content
      display flex
      background #141d27
      font-size 0
      .content-left
        flex 1
        .logo-wrapper
          display inline-block // 在使用inline-block的时候，要消除间隙的话，需要给父元素加上font-size: 0
          vertical-align top
          position relative
          top -10px
          margin 0px 12px
          padding 6px
          width 56px
          height 56px
          box-sizing border-box // 用border-box盒模型
          border-radius 50%
          background #141d27
          .logo
            width 100%
            height 100%
            border-radius 50%
            background #29343c
            text-align center
            &.highlight
              background rgb(0,160,220);
            .icon-shopping_cart
              font-size 24px
              line-height 44px
              color #7f858a
              &.highlight
                color rgb(255,255,255)
          .num
            position absolute
            top 0
            right 0
            width 24px
            height 16px
            line-height 16px
            text-align center
            border-radius 16px
            font-size 9px
            font-weight 700
            color #ffffff
            background rgb(240,20,20)
            box-shadow 0 4px 8px 0 rgba(0,0,0,0.4)
        .price
          display inline-block
          vertical-align top
          margin-top 12px
          padding-right 12px
          line-height 24px
          box-sizing border-box // 用border-box盒模型
          border-right 1px solid rgba(255,255,255,0.1)
          font-size 16px
          font-weight 700
          color rgba(255,255,255,0.4)
          &.highlight
            color rgb(255,255,255)
        .desc
          display inline-block
          vertical-align top
          line-height 24px
          margin 12px 0px 0px 12px
          font-size 10px
          font-weight 700
          color rgba(255,255,255,0.4)
      .content-right
        flex 0 0 105px // 固定宽度
        width 105px
        .pay
          text-align center
          font-size 12px
          height 48px
          line-height 48px
          font-weight 700
          background #29333b
          color #8b8e91
          &.not-enough
            background #29333b
          &.enough
            background #40b682
            color rgb(255,255,255)
            font-size 18px
    .ball-container
      .ball
        // 小球最终落点位置
        position fixed // fixed布局，因为小球的位置是相对于视口的
        // left 32px
        // bottom 22px
        left 47px
        bottom 43px
        z-index 200
        // background yellow
        // &.drop-enter
        transition all 0.4s cubic-bezier(.09,-0.5,.82,.62)
        .inner
          width 16px
          height 16px
          border-radius 50%
          background red
          transition all 0.4s
    .shopcart-list
      position absolute
      top 0
      left 0
      z-index -1
      width 100%
      transform translate3d(0,-100%,0) // 小技巧：-100%相当于当前自身的高度
      &.fold-enter-active, &.fold-leave-active
        transition all 0.5s
        transform translate3d(0,-100%,0) // 小技巧：-100%相当于当前自身的高度
      &.fold-enter,&.fold-leave-to
        transition all 0.5s
        transform translate3d(0,0,0)
      .list-header
        height 40px
        line-height 40px
        padding 0 18px
        background #f3f5f7
        border-bottom 1px solid rgba(7,17,27,0.1)
        .title
          float left
          font-size 14px
          color rgb(7,17,17)
        .empty
          float right
          padding-right: 8px;
          font-size 12px
          color rgb(0,160,220)
      .list-content
        padding 0 18px
        max-height 217px
        background #fff
        overflow hidden
        .food
          position relative
          padding 12px 0
          box-sizing border-box
          border-1px(rgba(7,17,27,0.1))
          .name
            line-height 24px
            font-size 14px
            color rgb(7,17,27)
          .price
            position absolute
            right 90px
            bottom 12px
            line-height 24px
            font-size 14px
            font-weight 700
            color rgb(240,20,20)
          .cartcontrol-wrapper
            position absolute
            right 0px
            bottom 6px
  .list-mask
    position fixed
    top 0
    left 0
    width 100%
    height 100%
    z-index 40
    background rgba(7,17,27,0.6);
    backdrop-filter blur(10px)
    &.mask-enter,&.mask-leave-to
      opacity 0
      transition all 0.5s
    &.mask-enter-active,&mask-leave-active
      // background rgba(7,17,27,0.6);
      backdrop-filter blur(10px)
      transition all 0.5s
</style>
